package common

import (
	"fmt"

	"gitee.com/wangshh_123/cross-pay-go/src/database"
	"gitee.com/wangshh_123/cross-pay-go/src/models"
)

// GetCardNicknames 根据卡片ID列表获取卡片昵称映射
func GetCardNicknames(cardIDs []string) (map[string]string, error) {
	if len(cardIDs) == 0 {
		return make(map[string]string), nil
	}

	// 从数据库中查询卡片昵称
	var cards []models.UserCard
	if err := database.DB.Where("card_id IN ?", cardIDs).Find(&cards).Error; err != nil {
		return nil, fmt.Errorf("query card nicknames failed: %v", err)
	}

	// 创建卡片ID到昵称的映射
	cardNicknames := make(map[string]string)
	for _, card := range cards {
		cardNicknames[card.CardID] = card.NikeName
	}

	return cardNicknames, nil
}

// AddCardNicknamesToData 为数据结构添加卡片昵称
func AddCardNicknamesToData(data interface{}) error {
	// 获取所有卡片的ID
	cardIDs := make([]string, 0)

	// 根据不同的数据结构类型提取卡片ID
	switch v := data.(type) {
	case []map[string]interface{}:
		for _, item := range v {
			if cardID, ok := item["cardId"].(string); ok && cardID != "" {
				cardIDs = append(cardIDs, cardID)
			}
		}
	case map[string]interface{}:
		if items, ok := v["data"].([]interface{}); ok {
			for _, item := range items {
				if itemMap, ok := item.(map[string]interface{}); ok {
					if cardID, ok := itemMap["cardId"].(string); ok && cardID != "" {
						cardIDs = append(cardIDs, cardID)
					}
				}
			}
		}
	default:
		return fmt.Errorf("unsupported data type: %T", data)
	}

	// 获取卡片昵称映射
	cardNicknames, err := GetCardNicknames(cardIDs)
	if err != nil {
		return err
	}

	// 为数据结构添加卡片昵称
	switch v := data.(type) {
	case []map[string]interface{}:
		for i := range v {
			if cardID, ok := v[i]["cardId"].(string); ok {
				if nickname, exists := cardNicknames[cardID]; exists {
					v[i]["cardNickname"] = nickname
				}
			}
		}
	case map[string]interface{}:
		if items, ok := v["data"].([]interface{}); ok {
			for _, item := range items {
				if itemMap, ok := item.(map[string]interface{}); ok {
					if cardID, ok := itemMap["cardId"].(string); ok {
						if nickname, exists := cardNicknames[cardID]; exists {
							itemMap["cardNickname"] = nickname
						}
					}
				}
			}
		}
	}

	return nil
}
